package vn.bang.communication;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class Communicator {

	private DatagramSocket datagramSocket;
	
	/**
	 * @param datagramSocket
	 */
	public Communicator(DatagramSocket datagramSocket) {
		this.datagramSocket = datagramSocket;
	}
	
	/**
	 * @param command
	 * @throws IOException
	 */
	public void sendCommand(String statement, InetAddress ip, int port) throws IOException {
		final byte[] sendData = statement.getBytes();
		DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, ip, port);
		datagramSocket.send(sendPacket);
	}
	
	/**
	 * @param command
	 * @throws IOException
	 */
	public void sendCommand(Command command, InetAddress ip, int port) throws IOException {
		sendCommand(command.toString(), ip, port);
	}
	
	/**
	 * @return
	 * @throws IOException if an I/O error occurs.
	 */
	public Command listenCommand() throws IOException {
		final byte[] data = receiveData();
		return new Command(data);
	}
	
	public void close() {
		datagramSocket.close();
	}
	
	/**
	 * @return
	 * @throws IOException if an I/O error occurs.
	 */
	private byte[] receiveData() throws IOException {
		final byte[] receiveData = new byte[1024];
		DatagramPacket receivePacket = new DatagramPacket(receiveData,
				receiveData.length);
		datagramSocket.receive(receivePacket);
		return receiveData;
	}
	
}
